package org.opens.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.consul.serviceregistry.ConsulRegistration;
import org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistry;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * 该配置类的作用与spring.cloud.consul.discovery.deregister属性值为true的效果相同, 在使用过程中发现当这个属性配置为true时服务停掉并不会
 * 剔除掉这个服务, 所以在网上查询到了这个配置类.
 *
 * @author by zhangyuming
 * @date 2023/1/28
 */
@Component
@Slf4j
public class ConsulConfig {

    @Autowired(required = false)
    private ConsulServiceRegistry consulServiceRegistry;

    @Autowired
    private ConsulRegistration reg;

    @EventListener(ContextClosedEvent.class)
    public void doUnRegister(ContextClosedEvent contextClosedEvent) {
        log.info("这是注册对象。。。。。。。。。。。。。。。" + consulServiceRegistry.getClass());
        if (null != consulServiceRegistry) {
            // 取消注册后会打印日志: 2023-01-28 11:47:30.015  INFO 9532 --- [      Thread-16] o.s.c.c.s.ConsulServiceRegistry          : Deregistering service with consul: consul-client-ad951694f99267810ac9e6d55671bf8b
            consulServiceRegistry.deregister(reg);
        }

    }

}
